package authservice

import (
	"context"
	"fmt"
	"games.com/server/internal/pkg/config"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
)

var (
	insertUserSQL  = `INSERT INTO users (username, password) VALUES (?, ?)`
	selectUserSQL  = `SELECT username, password FROM users WHERE username = ?`
	selectUsersSQL = `SELECT username, password FROM users`
)

type authDAO struct {
	db *sqlx.DB
}

func NewAuthDAO(config *config.Config) (*authDAO, error) {
	ad := &authDAO{}

	log.Println(config.Dsn)

	db, err := sqlx.Connect("mysql", config.Dsn)
	if err != nil {
		return nil, fmt.Errorf("failed to open mysql connection, dsn:%s, err:%w", config.Dsn, err)
	}

	ad.db = db
	return ad, nil
}

func (ad *authDAO) InsertUser(ctx context.Context, user *User) error {
	_, err := ad.db.ExecContext(ctx, insertUserSQL, user.Username, user.Password)
	if err != nil {
		return err
	}

	return nil
}

func (ad *authDAO) QueryUser(ctx context.Context, username string) (*User, error) {
	var user User

	err := ad.db.GetContext(ctx, &user, selectUserSQL, username)
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func (ad *authDAO) QueryUserList(ctx context.Context) ([]*User, error) {
	var users []*User

	err := ad.db.SelectContext(ctx, &users, selectUsersSQL)
	if err != nil {
		return nil, err
	}

	return users, nil
}
